// message.js
// Implement message reading and notification. Note that 'message' means 
// those sent between users while 'messaging' means those sent between 
// extension components.

var CurrentUnreadMessage = 0;
var ShowMessageNotification = (function(){});
function UpdateBrowserAction(state, badge)
{
	var normal_icon = "images/icons/qshpan_19.png";
	var grey_icon = "images/icons/qshpan_19_grey.png";
	var new_icon;
	var new_title;
	var new_badge = badge || "";
	var badge_bgcolor = "#ff0000";

	CurrentUnreadMessage = badge || "";

	if(state == "online")
	{
		new_icon = normal_icon;
		if(badge)
			new_title = "您有 " + badge + " 条未读消息";
		else
			new_title = "Riverside Plus";
	}
	else if(state == "offline")
	{
		new_icon = grey_icon;
		new_title = "Riverside Plus - 您当前未登录";
	}
	else if(state == "network-error")
	{
		new_icon = grey_icon;
		new_title = "Riverside Plus - 网络无法正常连接";
		new_badge = "×";
		badge_bgcolor = "#cccccc";
	}

	chrome.browserAction.setBadgeText({text: new_badge});
	chrome.browserAction.setBadgeBackgroundColor({color: badge_bgcolor});
	new_icon && chrome.browserAction.setIcon({path: new_icon});
	new_title && chrome.browserAction.setTitle({title: new_title});
}

function UpdateMessageCount()
{
	XHR.SendRequest("/", (function(xhr)
	{
		var windid = xhr.responseText.match(/var\s*windid\s*=\s*'(.*?)';/);
		var result = xhr.responseText.match(
			/<span id="msgnum_show">(\d*)<\/span>/);
		if(result)
		{
			UpdateBrowserAction("online", result[1]);
			Options.Notifications.NewMessageNotification && 
				ShowMessageNotification();
		}
		else if(windid && windid[1])
			UpdateBrowserAction("online");
		else
			UpdateBrowserAction("offline");
	}), (function()
	{
		UpdateBrowserAction("network-error");
	}) );
}

var MessageEntryRegEx_String = '<td><a href="u\\.php\\?action=show&uid=(\\d+)">(.*?)</a></td>\\s*<td><a href="message\\.php\\?action=(read|readn|readpub)&mid=(\\d+)">(.*?)</a></td>\\s*<td>(.*?)</td>';
var MessageEntryRegEx = new RegExp();
var MessageEntryRegExG = new RegExp();
MessageEntryRegEx.compile(MessageEntryRegEx_String, "i");
MessageEntryRegExG.compile(MessageEntryRegEx_String, "ig");

function ReadNewMessages(callback)
{
	XHR.SendRequest("/message.php?type=newmsg", (function(xhr)
	{
		var results = [];
		var messages = xhr.responseText.match(
			/<tr><td colspan="5"><b>未读(个人|系统|群发)短消息<\/b><\/td><\/tr>[\s\S]*?<\/table>/);
		if(!messages)
		{
			UpdateBrowserAction();
			callback(results);
			return;
		}
		var entries = messages[0].match(MessageEntryRegExG);
		if(!entries)
		{
			UpdateBrowserAction();
			callback(results);
			return;
		}
		entries.forEach(function(entry)
		{
			var matches = entry.match(MessageEntryRegEx);
			if(matches)
				results[results.length] = 
				{
					fromUid: matches[1], 
					fromUser: matches[2], 
					actionId: matches[3], 
					id: matches[4], 
					title: matches[5], 
					time: matches[6], 
				};
		});
		//UpdateBrowserAction("online", results.length.toString());
		UpdateMessageCount();
		callback(results);
	}), (function(xhr)
	{
		callback();
	}));
}

function GetMessageURL_PathName(message)
{
	return "/message.php?action=" + message.actionId + "&mid=" + 
		message.id;	
}

function ShowMessage(message)
{
	var pathname = GetMessageURL_PathName(message);
	var fullurl = XHR.GetURL(pathname);
	if(message.fromUser == "SYSTEM" && message.fromUid == "0" && 
		/^Hi，.*?@你了$/.test(message.title))
	{
		XHR.SendRequest(pathname, (function(xhr)
		{
			var target = xhr.responseText.match(
				/<a href="(.*?)">点这里看看吧<\/a>/);
			if(target && target[1])
			{
				var topic_at = target[1].match(
					/^\/?job\.php\?action=topost&tid=(\d+)&pid=$/);
				if(topic_at && topic_at[1])
					CreateTab("read.php?tid=" + topic_at[1]);
				else
					CreateTab(target[1]);
			}
			else
				CreateTab(pathname);
		}), (function()
		{
			CreateTab(pathname);
		}));
	}
	else
		CreateTab(pathname);
}

var lastMessageId = "";
var lastMessageTime = new Date(0);
ShowMessageNotification = (function(){ReadNewMessages(function(results)
{
	if(results && results[0] && results[0].id != lastMessageId && 
		(new Date(results[0].time)) >= lastMessageTime)
	{
		lastMessageId = results[0].id;
		lastMessageTime = new Date(results[0].time);
		ShowNotification("message", {
			fromUser: results[0].fromUser, 
			title: results[0].title, 
			}, (function()
		{
			ShowMessage(results[0]);
		}));
	}
})});

(chrome.extension.onMessage || chrome.extension.onRequest).addListener(
function(message, sender, sendResponse)
{
	if(message.name && message.name == "updateMessageCount" && 
		message.value != undefined && /^(\d*|\?)$/.test(message.value))
	{
		if(message.value == "?") //TODO Update message definition
			UpdateBrowserAction("offline");
		else
			UpdateBrowserAction("online", message.value);
		if(message.value != "?" && Options.Domain.Preference == "custom")
		{
			var domain = ((sender.tab || {}).url || "").match(
				/^http:\/\/(.*?)\//);
			if(domain && domain[1])
				Options.Domain.Current = domain[1];
		}
	}
});

Options.Notifications.onChanged = (function()
{
if(Options.Notifications.UpdateUnreadMessageInterval)
{
	Timer.Add("UpdateMessageCount", UpdateMessageCount, 
		Options.Notifications.UpdateUnreadMessageInterval / 60, true, 
		DomainReady); //trigger at once if domain ready (domain.js)
}
else
{
	Timer.Remove("UpdateMessageCount");
	UpdateBrowserAction();
}
});
if(Options.Notifications.UpdateUnreadMessageInterval)
{
	Options.Notifications.onChanged();
	DomainReadyCallback = UpdateMessageCount; //defined in domain.js
}

